package KMP算法;

import java.security.PublicKey;

public class Solution3 {

    public int strStr(String haystack, String needle) {
        // 计算next数组
        int[] next = new int[needle.length()];
        getNext(next, needle);
        // KMP算法匹配
        int j = -1;
        for (int i = 0; i < haystack.length(); i++) {
            // 匹配失败
            while (j > -1 && haystack.charAt(i) != needle.charAt(j + 1)) j = next[j];
            // 匹配成功
            if (haystack.charAt(i) == needle.charAt(j + 1)) j++;
            // 模式串完全匹配
            if( j == needle.length() -1  )
                return i - j;
        }
        return -1;
    }

    public void getNext(int[] next, String s) {
        int j = -1; // i为后缀末尾，j为前缀末尾
        next[0] = j;
        for (int i = 1; i < s.length(); i++) {
            // 不相等 => 回退
            while (j > -1 && s.charAt(i) != s.charAt(j + 1)) j = next[j];
            // 相等
            if (s.charAt(i) == s.charAt(j + 1)) j++;
            next[i] = j;
        }
    }
}
